
function canvasDataURL(file) {
  var ready = new FileReader()
  /* 开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容. */
  ready.readAsDataURL(file)
  ready.onload = function() {
    let re = this.result
    return re
  }
}
function compressDataURL(path, obj, callback) {
  var img = new Image()
  img.src = path
  img.onload = function() {
    var that = this
    var quality = 0.7 // 默认图片质量为0.7
    var initSize = that.length
    var width = that.width
    var height = that.height

    // 如果图片大于四百万像素，计算压缩比并将大小压至400万以下
    var ratio
    if ((ratio = width * height / 4000000) > 1) {
      ratio = Math.sqrt(ratio)
      width /= ratio
      height /= ratio
    } else {
      ratio = 1
    }
    // 生成canvas
    var canvas = document.createElement('canvas')
    var ctx = canvas.getContext('2d')
    canvas.width = width
    canvas.height = height

    //   铺底色
    ctx.fillStyle = '#fff'
    ctx.fillRect(0, 0, canvas.width, canvas.height)

    // 如果图片像素大于100万则使用瓦片绘制
    var count
    if ((count = width * height / 1000000) > 1) {
      // 生成canvas
      var tCanvas = document.createElement('canvas')
      var tctx = tCanvas.getContext('2d')
      count = ~~(Math.sqrt(count) + 1) // 计算要分成多少块瓦片
      //  计算每块瓦片的宽和高
      var nw = ~~(width / count)
      var nh = ~~(height / count)

      tCanvas.width = nw
      tCanvas.height = nh

      for (var i = 0; i < count; i++) {
        for (var j = 0; j < count; j++) {
          tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh)

          ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh)
        }
      }
    } else {
      ctx.drawImage(img, 0, 0, width, height)
    }
    // 图像质量
    if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
      quality = obj.quality
    }
    // 进行最小压缩
    var base64 = canvas.toDataURL('image/jpeg', quality)

    console.log('压缩前：' + initSize)
    console.log('压缩后：' + base64.length)
    console.log('压缩率：' + ~~(100 * (initSize - base64.length) / initSize) + '%')

    // 回调函数返回base64的值
    callback(base64)
  }
}
/**
 * 将以base64的图片url数据转换为File
 * @param urlData
 *            用url方式表示的base64图片数据
 */
function convertBase64UrlToFile(urlData, fileName) {
  let arr = urlData.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], fileName || 'tmp.jpg', {type: mime})
}

function compress(file, maxSize, quality) {
  if (file.size / 1024 > maxSize) { // 大于size，进行压缩
    let dataUrl = canvasDataURL(file)
    compressDataURL(dataUrl, {
      quality: quality
    }, function(base64Codes) {
      let newFile = convertBase64UrlToFile(base64Codes, file.fileName)
      return newFile
    })
  } else { // 小于等于1M 原图上传
    return file
  }
}

export {
  compress, convertBase64UrlToFile
}
